package com.yeqifu.bus.controller;


import com.alibaba.fastjson.parser.JSONToken;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeqifu.bus.entity.*;
import com.yeqifu.bus.service.*;
import com.yeqifu.bus.vo.InportVo;
import com.yeqifu.bus.vo.OutportVo;
import com.yeqifu.sys.common.DataGridView;
import com.yeqifu.sys.common.ResultObj;
import com.yeqifu.sys.common.WebUtils;
import com.yeqifu.sys.entity.Dept;
import com.yeqifu.sys.entity.User;
import com.yeqifu.sys.service.IDeptService;
import com.yeqifu.sys.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.Math.abs;

/**
 * <p>
 * InnoDB free: 9216 kB 前端控制器
 * </p>
 *
 * @author 艾琦
 * @since 2020-12-19
 */
@AllArgsConstructor
@RestController
@RequestMapping("outport")
public class OutportController {

    IOutportService outportService;
    IInportService inportService;
    IProviderService providerService;
    IGoodsService goodsService;
    IDeptService deptService;
    IUserService userService;
    ICustomerService customerService;


    /**
     * 添加出库信息，传入出库信息
     * @param outportVo
     * @return
     */
    @RequestMapping("addOutport")
    public ResultObj addOutport(OutportVo outportVo) {
        try {
            //获得当前系统用户
            User user = (User) WebUtils.getSession().getAttribute("user");
            //设置操作人
            outportVo.setOperateperson(user.getName());
            //设置出库时间
            outportVo.setOutputtime(new Date());

            Dept dept = deptService.getById(outportVo.getWareHouseName());
            Dept pdept = deptService.getById(dept.getPid());
            outportVo.setWareHousePName(pdept.getId());


            // 修改出库表，还没有真正入库
            if (outportService.save(outportVo))
                return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
        return ResultObj.ADD_ERROR;
    }

    /**
     * t
     * 查询商品退货
     *
     * @param outportVo
     * @return
     */
    @RequestMapping("loadAllOutport")
    public DataGridView loadAllOuport(OutportVo outportVo) {
        //1.先通过session获得当前用户的ID
        User user =(User) WebUtils.getSession().getAttribute("user");
        Integer userId = user.getId();
        User user1 = userService.getById(userId);
        IPage<Outport> page = new Page<Outport>(outportVo.getPage(), outportVo.getLimit());
        QueryWrapper<Outport> queryWrapper = new QueryWrapper<Outport>();

        // 看有没有父类
        Dept testdept = deptService.getById(user1.getDeptid());
        // 如果是区域或者仓库
        if (testdept.getPid() != 0)
            queryWrapper.eq("ware_house_name",user1.getDeptid()).or().eq("ware_house_p_name",user1.getDeptid());

        //对供应商进行查询
        queryWrapper.eq(outportVo.getProviderid() != null && outportVo.getProviderid() != 0, "providerid", outportVo.getProviderid());
        //对商品进行查询
        queryWrapper.eq(outportVo.getGoodsid() != null && outportVo.getGoodsid() != 0, "goodsid", outportVo.getGoodsid());
        //对时间进行查询要求大于开始时间小于结束时间
        queryWrapper.ge(outportVo.getStartTime() != null, "outputtime", outportVo.getStartTime());
        queryWrapper.le(outportVo.getEndTime() != null, "outputtime", outportVo.getEndTime());
        //通过进货时间对商品进行排序
        queryWrapper.orderByDesc("outputtime");
        IPage<Outport> page1 = outportService.page(page, queryWrapper);
        List<Outport> records = page1.getRecords();
        for (Outport ouport : records) {
            Provider provider = providerService.getById(ouport.getProviderid());
            //设置供应商姓名
            if (provider != null)
                ouport.setProvidername(provider.getProvidername());
            Goods goods = goodsService.getById(ouport.getGoodsid());
            if (goods != null) {
                //设置商品名称
                ouport.setGoodsname(goods.getGoodsname());
                //设置商品规格
                ouport.setSize(goods.getSize());
                // 设置商品类型
                ouport.setType(goods.getType());
            }
            Dept dept = deptService.getById(ouport.getWareHouseName());
            Dept pdept = deptService.getById(dept.getPid());
            // 设置仓库地区
            if (pdept != null) {
                ouport.setWareHousePName(pdept.getId());
                ouport.setWareHousePID(pdept.getName( ));
            }

            // 设置仓库名称
            if (dept != null)
                ouport.setWareHouseID(dept.getName());
            //设置超市名称
            Customer customer = customerService.getById(ouport.getCustomerId());
            if (customer != null)
                ouport.setCustomerName(customer.getCustomername());

        }
        return new DataGridView(page1.getTotal(), page1.getRecords());
    }

    /**
     * 删除出库信息
     *
     * @param id
     * @return
     */
    @RequestMapping("deleteOutport")
    public ResultObj deleteOutport(Integer id) {
        try {
            outportService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 撤回订单/退回订单，
     * 业务管理员 撤回订单只能撤回状态为 0 的订单
     * 仓库管理员 退回订单，可以退回状态为 1 或 0 的订单
     * */
    @RequestMapping("recallOutport")
    public ResultObj recallOutport(Integer id, @RequestParam int type){
        try {
            Outport outport = outportService.getById(id);
            if (type == 0)
                outport.setStatus(4);
            else if (type == 1)
                outport.setStatus(3);
            if (outportService.recallById(outport,type))
                return ResultObj.RECALLINPORT_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.RECALLINPORT_ERROR_2;
        }
        return ResultObj.RECALLINPORT_ERROR_1;
    }

    /**
     * 业务管理员修改出库商品，只能修改状态为 0 的订单
     * */
    @RequestMapping("updateOutport")
    public ResultObj updateOutport(OutportVo outportVo) {
        try {
            if (outportService.updateById(outportVo))
                return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
        return ResultObj.UPDATE_ERROR;
    }

    /**
     * 仓库实际出库，此操作是仓库管理员操作的，实际出库
     * @param outportVo
     * @return
     */

    @RequestMapping("realAddOutport")
    public ResultObj realAddOutport(OutportVo outportVo) {
        try {
            if (outportService.realSave(outportVo))
                return ResultObj.REALOUT_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultObj.REALOUT_ERROR;
    }

    /**
     * 获取出库商品的信息(近似于销售记录)用于季度统计。
     */
    @ResponseBody
    @RequestMapping("loadQuarterSales")
    public Map<String,Object> loadQuarterSales(@RequestParam(value = "goodsid", defaultValue = "") int goodsid,
                                             @RequestParam(value = "year", defaultValue = "") String year)
    {
        List<Outport> outport= outportService.loadMonthSales(goodsid); //获取商品的出库情况
        List<Inport> inport= inportService.loadYearSales(goodsid); //获取商品的入库情况
        int[] InQuartersum = new  int[4];//进库季度数量数组初始化
        int[] OutQuartersum = new  int[4];//出库季度数量数组初始化
        int a = Integer.parseInt(year);//将年份数据化
        System.out.println(a);
        for(int i = 0 ; i < inport.size(); i++)
        {
            Calendar calendar1 = Calendar.getInstance();
            Calendar calendar2 = Calendar.getInstance();
            calendar1.setTime(inport.get(i).getInporttime());//计算日期里面的的年份
            calendar2.setTime(inport.get(i).getInporttime());//计算日期里面的的年份
            int year1=calendar1.get(Calendar.YEAR);
            int month=calendar2.get(Calendar.MONTH);
            month=month+1;
            if(year1==a)//选择的年份
            {
                System.out.println(inport.get(i).getInporttime());
                if (month==1||month==2||month==3)//一月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    InQuartersum[0]+=n;
                }
                else if (month==4||month==5||month==6)//二月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    InQuartersum[1]+=n;
                }
                else if (month==7||month==8||month==9)//三月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    InQuartersum[2]+=n;
                }
                else if (month==10||month==11||month==12)//四月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    InQuartersum[3]+=n;
                }
            }
        }

        for(int i = 0 ; i < outport.size(); i++)
        {
            Calendar calendar1 = Calendar.getInstance();
            Calendar calendar2 = Calendar.getInstance();
            calendar1.setTime(outport.get(i).getOutputtime());//计算日期里面的的年份
            calendar2.setTime(outport.get(i).getOutputtime());//计算日期里面的的年份
            int year1=calendar1.get(Calendar.YEAR);
            int month=calendar2.get(Calendar.MONTH);
            month=month+1;
            if(year1==a)//选择的年份
            {
                if (month==1||month==2||month==3)//一季度
                {
                    int n;
                    n=outport.get(i).getNumber();
                    OutQuartersum[0]+=n;
                }
                else if (month==4||month==5||month==6)//二季度
                {
                    int n;
                    n=outport.get(i).getNumber();
                    OutQuartersum[1]+=n;
                }
                else if (month==7||month==8||month==9)//三季度
                {
                    int n;
                    n=outport.get(i).getNumber();
                    OutQuartersum[2]+=n;
                }
                else if (month==10||month==11||month==12)//四季度
                {
                    int n;
                    n=outport.get(i).getNumber();
                    OutQuartersum[3]+=n;
                }
            }
        }
        System.out.println(Arrays.toString(InQuartersum));
        System.out.println(Arrays.toString(OutQuartersum));
        Map<String,Object> map = new HashMap<String, Object>();
        /*map.put("goodsname", goodsname);*/
        map.put("InQuartersum", InQuartersum);
        map.put("OutQuartersum", OutQuartersum);
        return map;
    }

    /**
     * 获取入库和出库商品的信息(近似于销售记录)用于月份统计。
     */
    @ResponseBody
    @RequestMapping("loadMonthSales")
    public Map<String,Object> loadMonthSales(@RequestParam(value = "goodsid", defaultValue = "")int goodsid,
                                             @RequestParam(value = "year", defaultValue = "") String year)
    {
        List<Outport> outport= outportService.loadMonthSales(goodsid); //获取商品的出库情况
        List<Inport> inport= inportService.loadYearSales(goodsid); //获取商品的入库情况
        int[] Insum = new  int[12];//进库数量数组初始化
        int a = Integer.parseInt(year);//将年份数据化
        System.out.println(a);
        for(int i = 0 ; i < inport.size(); i++)
        {
            Calendar calendar1 = Calendar.getInstance();
            Calendar calendar2 = Calendar.getInstance();
            calendar1.setTime(inport.get(i).getInporttime());//计算日期里面的的年份
            calendar2.setTime(inport.get(i).getInporttime());//计算日期里面的的年份
            int year1=calendar1.get(Calendar.YEAR);
            int month=calendar2.get(Calendar.MONTH);
            month=month+1;
            if(year1==a)//选择的年份
            {
                System.out.println(inport.get(i).getInporttime());
                if (month==1)//一月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[0]+=n;
                }
                else if (month==2)//二月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[1]+=n;
                }
                else if (month==3)//三月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[2]+=n;
                }
                else if (month==4)//四月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[3]+=n;
                }
                else if (month==5)//五月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[4]+=n;
                }
                else if (month==6)//六月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[5]+=n;
                }
                else if (month==7)//七月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[6]+=n;
                }
                else if (month==8)//八月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[7]+=n;
                }
                else if (month==9)//九月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[8]+=n;
                }
                else if (month==10)//十月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[9]+=n;
                }
                else if (month==11)//十一月
                {
                    int n;
                    n=inport.get(i).getNumber();
                    Insum[10]+=n;
                }
                else if (month==12)//十二月
                {
                    int n = inport.get(i).getNumber();
                    Insum[11] += n;
                }
            }
        }

        //计算出库的数量
        int[] Outsum = new  int[12];//进库数量数组初始化
        for(int i = 0 ; i < outport.size(); i++)
        {
            Calendar calendar1 = Calendar.getInstance();
            Calendar calendar2 = Calendar.getInstance();
            calendar1.setTime(outport.get(i).getOutputtime());//计算日期里面的的年份
            calendar2.setTime(outport.get(i).getOutputtime());//计算日期里面的的年份
            int year1=calendar1.get(Calendar.YEAR);
            int month=calendar2.get(Calendar.MONTH);
            month=month+1;
            if(year1==a)//选择的年份
            {
                if (month==1)//一月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[0]+=n;
                }
                else if (month==2)//二月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[1]+=n;
                }
                else if (month==3)//三月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[2]+=n;
                }
                else if (month==4)//四月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[3]+=n;
                }
                else if (month==5)//五月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[4]+=n;
                }
                else if (month==6)//六月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[5]+=n;
                }
                else if (month==7)//七月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[6]+=n;
                }
                else if (month==8)//八月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[7]+=n;
                }
                else if (month==9)//九月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[8]+=n;
                }
                else if (month==10)//十月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[9]+=n;
                }
                else if (month==11)//十一月
                {
                    int n;
                    n=outport.get(i).getNumber();
                    Outsum[10]+=n;
                }
                else if (month==12)//十二月
                {
                    int n = outport.get(i).getNumber();
                    Outsum[11] += n;
                }
            }
        }
        int  []  Diffsum = new  int[12];//进库数量数组初始化
        for(int i = 0 ; i < 12; i++)
        {
            Diffsum[i]=Math.abs(Insum[i]-Outsum[i]);
        }
        System.out.println(Arrays.toString(Insum));
        System.out.println(Arrays.toString(Outsum));
        System.out.println(Arrays.toString(Diffsum));
        Map<String,Object> map = new HashMap<String, Object>();
       /* map.put("goodsname", goodsname);*/
        map.put("Insum", Insum);
        map.put("Outsum", Outsum);
        map.put("Diffsum",Diffsum);
        return map;
    }



}

